﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using PanasonicWarranty.Business;
using System.Web.Services;
using System.Text;
using System.Data.Linq;
using Utils;

namespace PanasonicWarranty.UI
{
    public partial class UnitManagement : BasePage
    {
        public int treeID
        {
            get
            {
                if (ViewState["TreeID"] == null) return 0;
                return Convert.ToInt32(ViewState["TreeID"]);
            }
            set
            {
                ViewState["TreeID"] = value;
            }
        }

        public string CheckAddOrEdit
        {
            get
            {
                return (string)ViewState["CheckAddOrEdit"];
            }
            set
            {
                ViewState["CheckAddOrEdit"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadUnit();
                if (CurUser.AgencyID.HasValue)
                {
                    RadTreeNodeEventArgs ex = new RadTreeNodeEventArgs(new RadTreeNode());
                    ex.Node.Value = CurUser.AgencyID.ToString();
                    RadTreeView_NodeClick(RadTreeView, ex);
                    CheckedNodeByValue(CurUser.AgencyID.Value.ToString());
                }
            }
        }

        private void CheckedNodeByValue(string value)
        {
            RadTreeNode node = RadTreeView.FindNodeByValue(value);
            if (node != null)
                node.Selected = true;
        }

        private void LoadUnit()
        {
            var units = pa_Agency.GetAll().OrderBy(p => p.Level);
            RadTreeView.DataSource = units;
            RadTreeView.DataFieldID = "AgencyID";
            RadTreeView.DataFieldParentID = "ParentID";
            RadTreeView.DataValueField = "AgencyID";
            RadTreeView.DataTextField = "AgencyName";
            RadTreeView.DataBind();
            RadTreeView.ExpandAllNodes();
            BindDropDownUnit();
        }

        private void BindDropDownUnit()
        {
            ddlParentUnit.Items.Add(new ListItem("--Select Item--", string.Empty));
            List<pa_Agency> units = pa_Agency.GetAll().OrderBy(p => p.Level).ToList();
            foreach (var item in units)
            {
                ddlParentUnit.Items.Add(new ListItem(item.AgencyName.ShowNameLevel(item.Level), item.AgencyID.ToString()));
                ddlUnit.Items.Add(new ListItem(item.AgencyName.ShowNameLevel(item.Level), item.AgencyID.ToString()));
            }
        }

        private void SetControls(bool edit)
        {
            CtrEdit.Enabled = edit;
        }

        private void SetControlsEdit(bool edit, string name)
        {
            CtrEdit.Visible = edit;
            btnSave.Text = name;
        }

        private void Clear()
        {
            txtUnitName.Text = string.Empty;
            txtZone.Text = string.Empty;
            ddlParentUnit.SelectedValue = "";
        }

        protected void RadTreeView_ContextItemClick(object sender, Telerik.Web.UI.RadTreeViewContextMenuEventArgs e)
        {
            if (!CheckRole(Role.Write))
            {
                ShowMessageBox("Bạn không có quyền thực hiện chức năng này!");
                return;
            }
            switch (e.MenuItem.Value)
            {
                case "Add":
                    CheckAddOrEdit = "Add";
                    txtUnitName.Focus();
                    SetControlsEdit(true, "Save");
                    Clear();
                    treeID = 0;
                    hdfTreeID.Value = treeID.ToString();   
                    break;
                case "Delete":
                    treeID = Convert.ToInt32(e.Node.Value);
                    hdfTreeID.Value = e.Node.Value;
                    pa_Agency.Delete(treeID);
                    Response.Redirect(Request.RawUrl);
                    break;
                default:
                    break;
            }
        }

        protected void RadTreeView_NodeClick(object sender, RadTreeNodeEventArgs e)
        {
            if (treeID != Convert.ToInt32(e.Node.Value))
            {
                CheckAddOrEdit = "Edit";
                txtUnitName.Focus();
                treeID = Convert.ToInt32(e.Node.Value);
                hdfTreeID.Value = e.Node.Value;
                SetControlsEdit(true, "Update");
                pa_Agency objUnit = pa_Agency.GetByKey(treeID);
                if (objUnit != null)
                {
                    txtUnitName.Text = objUnit.AgencyName;
                    ddlParentUnit.SelectedValue = objUnit.ParentID.HasValue ? objUnit.ParentID.ToString() : "";
                    SetControls(true);
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Clear();
        }
        
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                pa_Agency objUnit = new pa_Agency();
                int? parentID = ddlParentUnit.SelectedValue == "" ? (int?)null : Convert.ToInt32(ddlParentUnit.SelectedValue);
                if(!CheckRole(Role.Write))
                    throw new Exception("Bạn không có quyền thực hiện chức năng này");
                switch (CheckAddOrEdit)
                {
                    case "Add":
                        if (!IsRootAdmin())
                        {
                            if (pa_Agency.CompareLevel(CurUser.AgencyID, parentID) < 1)
                            {
                                throw new Exception("Bạn không có quyền tạo đại lý không phải đại lý con");
                            }
                        }
                        objUnit.AgencyID = 0;
                        break;
                    case "Edit":
                        objUnit = pa_Agency.GetByKey(treeID);
                        if (!IsRootAdmin())
                        {
                            if (pa_Agency.CompareLevel(CurUser.AgencyID, objUnit.AgencyID)>0)
                            {
                                throw new Exception("Bạn không có quyền sửa đại lý này");
                            }
                            if (pa_Agency.CompareLevel(CurUser.AgencyID, parentID) < 1)
                            {
                                throw new Exception("Bạn không có quyền tạo đại lý không phải đại lý con");
                            }
                        }
                        break;
                }
                objUnit.AgencyName = txtUnitName.Text;
                objUnit.Ord = string.IsNullOrEmpty(txtOrder.Text.Trim()) ? 0 : int.Parse(txtOrder.Text.Trim());
                objUnit.ParentID = parentID;
                objUnit.Save();
                RedirectToPage(Request.RawUrl);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert(\"" + ex.Message + "\");", true);
            }
        }

        protected void btnClose_Click(object sender, EventArgs e)
        {
            CtrEdit.Visible = false;
        }

        //#region WebServices
        //[WebMethod]
        //public static object StaffGetById(Guid staffId, Guid unitId)
        //{
        //    return db.pepsi_Staffs
        //        .Where(p => p.StaffID == staffId)
        //        .Select(p=>new{
        //                p.StaffID,
        //                p.StaffCode,
        //                p.StaffName,
        //                p.Gender,
        //                p.Address,
        //                p.UnitID,
        //                p.StaffLevel,
        //                p.Actived,
        //                p.StaffTypeID,
        //                UnitName = p.pepsi_Unit.Name,
        //                PhoneNumber = db.fn_getStaffPhoneList(staffId)
        //            })
        //        .FirstOrDefault();
        //}

        //[WebMethod]
        //public static object StaffGetByUnitId(Guid unitId, int curentPage, int pageSize)
        //{
        //    int? totalRecord = 0;
        //    return db.sp_pepsi_StaffGetByUnit_Paging(unitId, curentPage, pageSize, ref totalRecord)
        //        .Select(p => new
        //        {
        //            p.StaffID,
        //            p.StaffCode,
        //            p.StaffName,
        //            p.Gender,
        //            p.Address,
        //            p.Actived,
        //            p.UnitID,
        //            p.UnitName,
        //            p.StaffType,
        //            p.StaffLevel
        //        });
        //}

        //[WebMethod]
        //public static bool StaffUpdate(Guid staffId, Guid unitId, string staffcode, string staffname, bool gender, string address, int stafflevel, short stafftype, bool actived, string phonenumber)
        //{
        //    try
        //    {
        //        pepsi_Staff staff = db.pepsi_Staffs.FirstOrDefault(p => p.StaffID == staffId);
        //        if (staff != null)
        //        {
        //            //Update staff
        //            staff.StaffCode = staffcode;
        //            staff.StaffName = staffname;
        //            staff.Gender = gender;
        //            staff.Address = address;
        //            staff.Actived = actived;
        //            staff.UnitID = unitId;
        //            staff.StaffLevel = stafflevel;
        //            staff.StaffTypeID = stafftype;
        //            db.SubmitChanges();
        //            //Update contact
        //            var contacts = db.pepsi_Contacts.Where(p => p.StaffID == staffId);
        //            if (contacts != null)//delete old contact
        //                db.pepsi_Contacts.DeleteAllOnSubmit(contacts);
        //            short i = 0;
        //            foreach (string item in phonenumber.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) //Re add contact
        //            {
        //                pepsi_Contact contact = new pepsi_Contact();
        //                contact.StaffID = staffId;
        //                contact.PhoneNumber = item.ToNormalPhoneNumber();
        //                if (!contact.ValidatePhoneNumber(contact.PhoneNumber))
        //                {
        //                    throw new Exception("Phone number is invalid!");
        //                }
        //                contact.OperatorID = contact.GetOperatorID();
        //                contact.Actived = true;
        //                contact.Priority = (++i);
        //                db.pepsi_Contacts.InsertOnSubmit(contact);
        //            }
        //            //Update User (Khi cập nhật lại Unit cho Staff thì Unit của User của staff đó phải được cập nhật theo)
        //            var user = db.pepsi_Users.FirstOrDefault(p => p.StaffID == staff.StaffID);
        //            if (user != null)
        //            {
        //                user.UnitID = unitId;
        //                //user.pepsi_Unit.ID = unitId;
        //            }
        //            db.SubmitChanges(ConflictMode.ContinueOnConflict);
        //            //db.Refresh(System.Data.Linq.RefreshMode.OverwriteCurrentValues, db.pepsi_Staffs);
        //            return true;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        throw ex;
        //    }
        //    return false;
        //}

        //[WebMethod]
        //public static void StaffInsert(string staffcode, string staffname, bool gender, string address, string phonenumber, int stafflevel, short stafftype, bool actived, Guid unitId)
        //{
        //    //Add new staff
        //    pepsi_Staff newStaff = new pepsi_Staff();
        //    newStaff.StaffID = Guid.NewGuid();
        //    newStaff.StaffCode = staffcode;
        //    newStaff.StaffName = staffname;
        //    newStaff.Gender = gender;
        //    newStaff.Address = address;
        //    newStaff.UnitID = unitId;
        //    newStaff.StaffID = newStaff.StaffID;
        //    newStaff.StaffLevel = stafflevel;
        //    newStaff.StaffTypeID = stafftype;
        //    newStaff.Actived = true;
        //    db.pepsi_Staffs.InsertOnSubmit(newStaff);
        //    //Add Contacts
        //    string[] phonelist = phonenumber.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
        //    short i = 0;
        //    foreach (string item in phonelist)
        //    {
        //        pepsi_Contact newContact = new pepsi_Contact();
        //        newContact.StaffID = newStaff.StaffID;
        //        newContact.PhoneNumber = item.ToNormalPhoneNumber();
        //        newContact.OperatorID = newContact.GetOperatorID();
        //        newContact.Actived = true;
        //        newContact.Priority = (++i);
        //        db.pepsi_Contacts.InsertOnSubmit(newContact);
        //    }
        //    //Commit Change to database
        //    db.SubmitChanges();
        //}

        //[WebMethod]
        //public static void StaffDeleteById(Guid staffId, Guid unitId)
        //{
        //    var staff = db.pepsi_Staffs.FirstOrDefault(p => p.StaffID == staffId);
        //    if (staff != null)
        //    {
        //        //Delete contact
        //        var contacts = db.pepsi_Contacts.Where(p => p.StaffID == staffId);
        //        if (contacts != null)
        //            db.pepsi_Contacts.DeleteAllOnSubmit(contacts);
        //        db.pepsi_Staffs.DeleteOnSubmit(staff);
        //        db.SubmitChanges();
        //    }
        //}

        //[WebMethod]
        //public static void StaffDeleteByListOfId(string listOfId, Guid unitId)
        //{
        //    //var deleteOjb = db.pepsi_Staffs.Where(p => listOfId.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Contains(p.StaffID.ToString()));
        //    //if (deleteOjb != null)
        //    //{
        //    //    foreach (var item in deleteOjb)
        //    //    {
        //    //        //Delete contact
        //    //        var contacts = db.pepsi_Contacts.Where(p => p.StaffID == item.StaffID);
        //    //        if (contacts != null)
        //    //            db.pepsi_Contacts.DeleteAllOnSubmit(contacts);
        //    //        //Delete 
        //    //    }
        //    //}
        //}

        //[WebMethod]
        //public static bool CheckExistsStaffCode(Guid? staffId, string staffcode)
        //{
        //    return pepsi_Staff.CheckExistsStaffCode(staffId, staffcode);
        //}

        //[WebMethod]
        //public static bool CheckValidPhoneNumber(string phonelist)
        //{
        //    return pepsi_Contact.CheckValidPhoneNumber(phonelist.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
        //}

        //[WebMethod]
        //public static bool CheckExistsPhoneNumber(Guid staffId, string phonelist)
        //{
        //    return pepsi_Contact.CheckExistsPhoneNumber(staffId, phonelist.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
        //}

        //[WebMethod]
        //public static bool checkPrivileges(Guid? unit1ID, Guid? unit2ID)
        //{
        //    if (db.fn_CompareUnitLevel(unit1ID, unit2ID) > 0)
        //        return false;
        //    return true;
        //}

        //#endregion

    }
}